package cn.wyl.service.Impl;

import cn.wyl.domain.BuyLog;
import cn.wyl.domain.Course;
import cn.wyl.dto.BuyDto;
import cn.wyl.feignclient.BuyFeignClient;
import cn.wyl.mapper.BuyLogMapper;
import cn.wyl.mapper.CourseMapper;
import cn.wyl.service.IBuyLogService;
import cn.wyl.util.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class BuyLogServiceImpl implements IBuyLogService {

    @Autowired
    private BuyLogMapper buyLogMapper;

    @Autowired
    private CourseMapper courseMapper;

    @Autowired
    private BuyFeignClient buyFeignClient;

    @Override
    @Transactional
    public AjaxResult save(BuyDto buyDto) {

        Long id = buyDto.getCourseId();
        //判断库存是否足够
        Course course = courseMapper.loadById(id);
        //如果库存不够就提醒用户
        //库存
        Integer saleCount = course.getSaleCount();
        //购买量
        Integer buyCount = buyDto.getBuyCount();
        if(buyCount > saleCount){
            throw new RuntimeException("库存不够了");
        }

        BuyLog buyLog = new BuyLog();
        //设置购买人
        buyLog.setUserId(buyDto.getUserId());
        //设置购买金额
        buyLog.setPayPrice(course.getPrice());
        //设置购买时间
        buyLog.setBuyTime(new Date());
        //设置购买数量
        buyLog.setBuyCount(buyDto.getBuyCount());
        //修改课程数量
        course.setSaleCount(saleCount-buyCount);
        AjaxResult upd = buyFeignClient.upd(course);
        //保存日志
        if(upd.getSuccess().equals(true)){
            buyLogMapper.save(buyLog);
        }
        return upd;
    }
}
